package com.ying.provider9001.controller;
import com.ying.provider9001.domain.DoMain;
import com.ying.provider9001.mapper.ProvMapper;
import com.ying.provider9001.pack.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;


@RestController
@RequestMapping("/prov")
public class Provider9001Controller {

    @Autowired
    ProvMapper provMapper;

    @Value("${server.port}")
    String port;

    @GetMapping("/get/{id}")
//    @HystrixCommand(fallbackMethod = "hystrixgetuser")
    public R getdomain(@PathVariable Long id) {

        if (id == 100) {
            throw new RuntimeException();
        }
        DoMain doMain = provMapper.selectById(id);
        R rr = new R();

        if (StringUtils.isEmpty(doMain)) {
            return rr.setTypeCode("300")
                    .setMessage("id为" + id + "数据不存在！！")
                    .setObject(new DoMain().setId(id).setContent("null"));
        } else {
            return rr.setTypeCode("200")
                    .setMessage("id为" + id + "数据查询成功！！当前端口为" + port + "提供的服务")
                    .setObject(doMain);
        }
    }

    public R hystrixgetuser(@PathVariable Long id) {

        System.out.println("------------------");
        return new R().setMessage("getdomain方法触发了熔断！");
    }


    @GetMapping("/delete/{id}")
    public R deletedomain(@PathVariable Long id) {

        DoMain doMain = provMapper.selectById(id);

        R rr = new R();

        if (StringUtils.isEmpty(doMain)) {
            return rr.setTypeCode("300")
                    .setMessage("id为" + id + "数据不存在！！")
                    .setObject(new DoMain().setId(id).setContent("null"));
        } else {
            provMapper.deleteById(id);
            return rr.setTypeCode("200")
                    .setMessage("id为" + id + "数据已经成功删除！！")
                    .setObject(doMain);
        }
    }

    @PostMapping("/insert")
    public R insertdomain(@RequestBody DoMain doMain) {

        System.out.println("provider" + doMain);
        provMapper.insert(doMain);

        return new R().setTypeCode("200")
                .setMessage("id为" + doMain.getId() + "数据添加成功！！")
                .setObject(doMain);
    }


    @PostMapping("/update")
    public R updatedomain(@RequestBody DoMain doMain) {

        System.out.println("provider" + doMain);
        provMapper.updateById(doMain);
        return new R().setTypeCode("200")
                .setMessage("id为" + doMain.getId() + "数据更新成功！！")
                .setObject(doMain);
    }

}
